package com.nmdl.test2.utils;

import android.util.Log;

/**
 * 锁设备解密加密工具类
 * Created by HP on 2017/5/24.
 */

public class DataProcessUtil {
    private static volatile DataProcessUtil mLockUtil;

    public static DataProcessUtil getInstance() {
        if (mLockUtil == null) {
            synchronized (DataProcessUtil.class) {
                if (mLockUtil == null) {
                    mLockUtil = new DataProcessUtil();
                }
            }
        }
        return mLockUtil;
    }

    protected DataProcessUtil() {

    }

    /**
     * @param command
     * @param data
     * @return
     */
    public byte[] makePacket(byte command, byte[] data) {
        byte[] buffer = new byte[data.length + 5];
        buffer[0] = (byte) 0x55;
        buffer[1] = (byte) data.length;
        buffer[2] = command;
        if (data != null && data.length > 0)
            for (int i = 0; i < data.length; i++) buffer[3 + i] = data[i];

        buffer[3 + data.length] = (byte) CheckSum(data);
        buffer[3 + data.length] += buffer[0];
        buffer[3 + data.length] += buffer[1];
        buffer[3 + data.length] += buffer[2];
        buffer[3 + data.length + 1] = (byte) 0xaa;
        Log.e("LockUtil", "makePacket: buffer = " + bytes2HexString(buffer));
        return buffer;
    }

    public byte[] makePacket1(byte command, byte[] data) {
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = (byte) 0x4A;
        buffer[1] = command;
        buffer[2] = (byte) data.length;
        if (data != null && data.length > 0)
            for (int i = 0; i < data.length; i++) buffer[3 + i] = data[i];
        Log.e("LockUtil", "makePacket: buffer = " + bytes2HexString(buffer));
        return buffer;
    }

    /**
     * 检测发送数据
     *
     * @param data
     * @return
     */
    private byte CheckSum(byte[] data) {
        byte sum = 0;
        if (data == null) return sum;
        for (int i = 0; i < data.length; i++)
            sum += data[i];
        return sum;
    }

    // add by yins

    /**
     * 16进制字符串转二进制字节数组
     *
     * @param s
     * @return
     */
    public byte[] hexStr2Bytes(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }

        return data;
    }

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public String bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }
}
